package com.oms.framework.web.service;

import com.oms.framework.util.ShiroUtils;
import com.oms.system.domain.SysMenu;
import com.oms.system.domain.SysRoleMenu;
import com.oms.system.domain.SysUser;
import com.oms.system.mapper.SysRoleMenuMapper;
import com.oms.system.service.ISysMenuService;
import com.oms.system.service.ISysUserService;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.oms.common.utils.security.PermissionUtils;

/**
 * RuoYi首创 js调用 thymeleaf 实现按钮权限可见性
 * 
 * @author lucas
 */
@Service("permission")
public class PermissionService {

    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysMenuService menuService;
    @Autowired
    private SysRoleMenuMapper roleMenuMapper;

    public String hasPermi(String permission) {
        return isPermittedOperator(permission) ? "" : "hidden";
    }

    public String hasRole(String role) {
        return hasRoleOperator(role) ? "" : "hidden";
    }

    /**
     * 判断用户是否拥有某个权限
     * 
     * @param permission 权限字符串
     * @return 结果
     */
    private boolean isPermittedOperator(String permission) {
        Long userId = ShiroUtils.getUserId();
        SysUser sysUser = userService.selectUser(userId);
        if(sysUser.getRemark() != null && sysUser.getRemark().equals("admin")){
            return true;
        }
        SysMenu sysMenu = menuService.getMenu(permission);
        SysRoleMenu sysRoleMenu = roleMenuMapper.getoleMenu(sysUser.getRoleId(), sysMenu.getMenuId());
        return sysRoleMenu != null;
//        return SecurityUtils.getSubject().isPermitted(permission);
    }

    /**
     * 判断用户是否拥有某个角色
     * 
     * @param role 角色字符串
     * @return 结果
     */
    private boolean hasRoleOperator(String role) {
        return SecurityUtils.getSubject().hasRole(role);
    }

    /**
     * 返回用户属性值
     *
     * @param property 属性名称
     * @return 用户属性值
     */
    public Object getPrincipalProperty(String property) {
        return PermissionUtils.getPrincipalProperty(property);
    }
}
